function isValueInArray(arr, val) {
	inArray = false;
	for (i = 0; i < arr.length; i++)
		if (val == arr[i])
			inArray = true;
	return inArray;
}

var pintaAmigo = {
	getId : function (amigo){
		 return amigo.getId().split('@')[0].replace(/\./g,'-');
	},	

	getGoogleId : function (amigo){
		 return amigo.getId().split('@')[0];
	},	
	
	/*
	getExternalData : function(amigoId){
		var extURL = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
		var extParams = {
			tags: "cat",
			tagmode: "any",
			format: "json"
		  };		
		$.getJSON(extURL, extParams,
		  function(data) {
			$.each(data.items, function(i,item){
			  $("<img/>").attr("src", item.media.m).appendTo("#fichaInfoExterna");
			  if ( i == 3 ) return false;
			});			
			gadgets.window.adjustHeight();			
		  });
	
	},
	*/
	getTwitter: function(){
		$.getJSON("http://search.twitter.com/search.json?q='groucho'&rpp=10&callback=?", function(data) {
			if($('#twitterTab').length == 0){
					$('#tabLabels').append('<li id="twitterTab" vclass="ui-state-default ui-corner-top"><a href="#twitter"> Twitter </a></li>');
			}
			if($('#twitter').length == 0){
				$('#tabWrap').append('<div id="twitter" class="tabContainer ui-tabs-panel ui-widget-content ui-corner-bottom"><ul class="properties"></ul></div>');
			}
			else{
				$('#twitter').html('<ul class="properties"></ul>');
			}
			$.each(data.results, function(i,item){
				$('#twitter .properties').append('<li class="content" id="label"><span class="term">' + item.from_user + '</span><span class="data">' + item.text +'</span></li>');
			});		
			
			gadgets.window.adjustHeight();				
          });		
	},
	
	getSocialGraph : function(amigo){			
		//https://profiles.google.com/u/0/nacho.saski/about .vcard
		var gadgetURL = "https://socialgraph.googleapis.com/otherme?q=";		
		/*
		var theId = pintaAmigo.getGoogleId(amigo);		
		var theURL = gadgetURL + theId + "@google.com,https://profiles.google.com/" + theId;
		var theURL  = "https://socialgraph.googleapis.com/geturl?domain=twitter.com&id=saski&type=rss&pretty=1"
alert("theURL: " + theURL);

		jQuery.ajax({
			url: theURL,
			dataType: "jsonp",			
			success: function(data) {
				alert(data);
				//$('#fichaInfoExterna').html(data);
			}
		});
		*/
		var extURL = "https://socialgraph.googleapis.com/geturl?";
		var extParams = {
			domain: "twitter.com",
			id: "saski",
			type: "rss",
			pretty: "1"			
		  };		
		$.getJSON(extURL, extParams, parseInfo);			
		function parseInfo(data) { 
			//alert(data);
			gadgets.window.adjustHeight();
		} 		
	},
	
	getBBVAData : function(amigoId){	
		amigoId = amigoId.split('@')[0].replace(/\./g,'');		
		var gadgetURL = "http://saski.com/indra/wave/widget-sandbox/php/";		
		var BBVAjsonData = "data.php";		
		
		jQuery.ajax({
			url: gadgetURL + BBVAjsonData,
			dataType: "json",
			data: ({id : amigoId}),
			beforeSend: function(xhr) {
				$('.loading').toggle();
				xhr.setRequestHeader("Accept", "application/json");
				xhr.setRequestHeader("Proxy-Authorization", "aml2aWVqbzpzYXNraTAwMQ==");
			},
			error: function(jqXHR, textStatus, errorThrown){
				alert( textStatus + " en la conexión" + errorThrown);
			},
			
			success: function(data) {
				$('.loading').toggle();
				
				var tabWrap = $('<div id="tabWrap"/>');
				var tabLabels = $('<ul/>', {'id':'tabLabels'});
				
				//Pinta Profile en #receiver
				var display = $('#receiver');
				
				var ficha = '<div class="ficha"><img alt="'+ data['profile']['nombre'] +'" src="'+ data['profile']['foto']+'" /><span class="name">'+ data['profile']['nombre'] +'</span></div>';				
	
				ficha +='<ul class="profile">';
					ficha +='<li> <span class="label">Id: </span><span class="data">'		+ data['profile']['cuenta'] +'</span></li>';
					ficha +='<li> <span class="label">Segmento: </span><span class="data">'		+ data['profile']['Segmento'] +'</span></li>';
					ficha +='<li> <span class="label">Edad: </span><span class="data">'		+ data['profile']['Edad'] +'</span></li>';
					ficha +='<li> <span class="label">Próxima cita: </span><span class="data">'		+ data['profile']['Próxima cita'] +'</span></li>';
					ficha +='<li> <span class="label">Ubicación: </span><span class="data">'		+ data['profile']['ubicacion']['ciudad'] + '  / ' +data['profile']['ubicacion']['pais'] +'</span></li>';
					ficha +='<li> <span class="label">Gestor: </span><span class="data">'		+ data['profile']['gestor']['nombre'] +'</span></li>';
					ficha +='<li> <span class="label">Usuario: </span><span class="data">'		+ data['profile']['gestor']['usuario'] +'</span></li>';
					ficha +='</ul>';			
				
				display.html(ficha).css('height','auto');
				
				//Pinta las pestañas, excluyendo Profile
				tabWrap.append(tabLabels);				
				
				$.each(data, function(key, val) {
					var label = data[key]['label'] || data[key]; 
					tabLabels.append('<li><a href="#'+ key +' "> '+ label+ '</a></li>');
					
					thisContent = $('<div/>', {
						'id': key,
						'class':'tabContainer',				
						html: '<ul class="properties"/>'
					});					
					
					$.each(val, function(first, second){
							if(typeof second === "string"){
								
									if (second.toLowerCase().indexOf("http") >= 0){// si es url, pinta la imagen
										var content = '<li class="content" id="' + first+ '"><span class="term">' + first + ': </span><span class="data"><img src="' + second + '" /></span></li>' ;									
									}
									else{ // si no, los valores
										var content = '<li class="content" id="' + first+ '"><span class="term">' + first + ': </span><span class="data">' + second + '</span></li>' ;								
									}
							}
							else{
								var innerContent = '';
								var content = '<li class="content" id="' + first+ '"><span class="term">' + first + ': </span><ul class="data">' ;
								$.each(second, function(innerProperty, innerValue){														
									innerContent += '<li class="innerProperty" id="property' + innerProperty+ '"><span class="innerProperty">' + innerProperty + ': </span><span class="innerValue">' + innerValue + '</span></li>' ;								
								});
								content += innerContent + '</ul></li>';
								//$(content).find('ul.properties').append(innerContent);		
							}
							thisContent.find('ul.properties').append(content);	
					});
					
					tabWrap.append(thisContent);
				});
												
				
				$('#content').show().html(tabWrap);				
				
				tabWrap.tabs();
				
				gadgets.window.adjustHeight();
			}
		   
		});
		
	},
	
	nuevoAmigo : function (amigo){ 
		newFriend = $('<li><a href="#" id="'+ amigo.getId(amigo) +'" class="partner"><img src="'+ amigo.getThumbnailUrl()+'" alt="'+ amigo.getDisplayName() +'"></a></li>').first().bind({
			click: function() {
				var friendId = pintaAmigo.getId(amigo) +"Ext";
				//pintaAmigo.getExternalData(amigo.getId());
				//pintaAmigo.getBBVAData(amigo.getId());
				//pintaAmigo.getSocialGraph(amigo);
				//pintaAmigo.getTwitter();
			},
			mouseenter: function() {
				var friendId = pintaAmigo.getId(amigo) +"Ext";				
				$('#'+friendId).css('display', 'block');
			},
			mouseleave: function(){
				var friendId = pintaAmigo.getId(amigo) +"Ext";
				$('#'+friendId).css('display', 'none');
			}
		});	
		//pinta ficha Hover
		newFriendExt = $('<p class="extended" id="'+pintaAmigo.getId(amigo)+'Ext"><img src="'+ amigo.getThumbnailUrl() +'" alt="'+ amigo.getDisplayName() +'"><span class="name">'+ amigo.getDisplayName() +'</span><span class="id">'+ amigo.getId() + '</span></p>');		
		
		$(newFriend).append(newFriendExt);
		$(newFriend).draggable({ snap: "#receiver", revert:true, opacity:"0.6", helper: "clone"  });
		$( "#receiver" ).droppable({
			hoverClass: "ui-state-active",
			drop: function( event, ui ) {						
				var allowed = ['nacho.saski@googlewave.com', 'nacho.saski@wavesandbox.com', 'nacho.viejo@wavesandbox.com', 'saski@demo.wave-in-a-box.org', 'j.mario.rios@googlewave.com'];
				var viewerId = wave.getViewer().getId();
				if (isValueInArray(allowed, viewerId)){
					droppedId = $(ui.draggable).find('.partner').attr('id');
					pintaAmigo.getBBVAData(droppedId);				
					$( this ).addClass( "ui-state-highlight" );
					$(ui.draggable).revert;
				}
				else
				{
					alert('no tienes permiso');
					return
				}
					
				
			}
		});
		
		$('ul#partnersList').append(newFriend);		
	}
}


function renderPartners() {	
	if (!wave.getParticipants()) {
			setMiniMessage('id0','no participants');
			return;
	}
	var amigos = wave.getParticipants();  
  
	setMiniMessage('id0','[Hay ' + amigos.length.toString() + ' participantes en el wave]');  
	$("ul#partnersList").html('');                

	for (var i = 0; i < amigos.length; ++i) {             

		var delta = {};		
		
		delta[amigos[i].getId()] = amigos[i];
		console.log("wave.getState(): "+ wave.getState());
		console.log("delta: "+ delta);
		wave.getState().submitDelta(delta);
		
        pintaAmigo.nuevoAmigo(amigos[i]);			
		gadgets.window.adjustHeight();
	}
 
	$('#close').bind({
		click: function() {
			$('#receiver').html('');
			$('#content').hide().html('');
		}
	}); 
	
	pintaAgenda();

	gadgets.window.adjustHeight();
}

function pintaAgenda(){
	var nombre = wave.getViewer().getDisplayName();
	var agenda = {};
	$('#agenda #viewerName').text(nombre);
}


function init() {

  
  if (wave && wave.isInWaveContainer()) {       
        //wave.setStateCallback(renderInfo);
		gadgets.window.adjustHeight();
        wave.setParticipantCallback(renderPartners);
  }  
}
gadgets.util.registerOnLoadHandler(init);   